//
//  DomainManager.swift
//  Mediaplayer
//
//  Created by bin hu on 2025/7/14.
//


import UIKit
import Alamofire

struct DomainHandleModel {
    let url: String
    var failureCount: Int
    var isBlocked: Bool { failureCount >= 5 }
}

class DomainManager {
    static let shared = DomainManager()
    private var domains: [DomainHandleModel]
    private var currentIndex: Int = 0
    private let queue = DispatchQueue(label: "com.domain.manager", attributes: .concurrent)
    
    init() {
        domains = [
            DomainHandleModel(url: "api1.example.com", failureCount: 0),
            DomainHandleModel(url: "api2.example.com", failureCount: 0)
        ]
        if let savedPath = UserDefaults.standard.string(forKey: "currentDomain") {
            currentIndex = domains.firstIndex { $0.url == savedPath } ?? 0
        }
    }
    
    /// 可用域名的个数就是最大重试次数
    var maxTryCount:Int {
        return domains.filter { $0.isBlocked == false }.count
    }
    
    var currentDomain: String {
        return domains[currentIndex].url
    }
    
    func getActiveDomain() -> String {
        queue.sync(flags: .barrier) {
            // 检查当前域名是否可用
            if !domains[currentIndex].isBlocked {
                return domains[currentIndex].url
            }
            
            // 轮询查找可用域名
            for i in 1..<domains.count {
                let nextIndex = (currentIndex + i) % domains.count
                if !domains[nextIndex].isBlocked {
                    currentIndex = nextIndex
                    return domains[nextIndex].url
                }
            }
            
            // 全部熔断时返回第一个
            return domains.first?.url ?? "api1.example.com"
        }
    }
    
    ///添加新域名
    func addDomain(_ domain: DomainHandleModel) {
        queue.sync {
            domains.append(domain)
        }
    }
    
    /// 移除不需要域名
    func removeDomain(at index: Int) {
        queue.sync {
            domains.remove(at: index)
            if currentIndex == index {
                currentIndex = 0
            }
        }
    }
    
    /// 成功
    func reportSuccess(for url: String) {
        queue.async(flags: .barrier) {
            if let index = self.domains.firstIndex(where: { $0.url == url }) {
                self.domains[index].failureCount = 0
                self.currentIndex = index
                UserDefaults.standard.set(url, forKey: "currentDomain")
            }
        }
    }
    
    /// 失败
    func reportFailure(for url: String) {
        queue.async(flags: .barrier) {
            if let index = self.domains.firstIndex(where: { $0.url == url }) {
                self.domains[index].failureCount += 1
                self.currentIndex += 1
                if self.currentIndex >= self.domains.count {
                    self.currentIndex = 0
                }
//                if index == self.currentIndex {
//                    _ = self.getActiveDomain() // 触发自动切换
//                }
            }
        }
    }
    
    /// 重置所有状态
    func resetAllDomains() {
        queue.async(flags: .barrier) {
            for i in 0..<self.domains.count {
                self.domains[i].failureCount = 0
            }
        }
    }
    
}

